package com.chenl.provider.DEMOS.Spring.Spring参数解析器;

import com.chenl.provider.DTO.UserInfo;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
@Configuration
public class MyResolver implements HandlerMethodArgumentResolver {
    /**
     * 当前方法返回true才会走下面那个resolveArgument（）方法,当前方法只会在每个接口第一次被调用的时候进行判断，之后判断结果会被缓存，不会每次都调用
     * @param parameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //带有CurrentUser注解的参数，并且此参数同时为UserInfo类，则返回true
        return parameter.hasParameterAnnotation(CurrentUser.class)&&parameter.getParameterType().isAssignableFrom(UserInfo.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer
            , NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String token = webRequest.getHeader("token");
        UserInfo userInfo=new UserInfo();
        userInfo.setAge(token);
        if (token==null){
            throw  new RuntimeException("请登陆后再进行操作！~");
        }
        return userInfo;
    }
}
